package main

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/gin-gonic/gin"
)

const (
	DefaultUrl = "https://mall.iytime.com/pages/index/index"
)

func main() {
	gin.SetMode(gin.ReleaseMode)

	rdb, err := getRdb()
	if err != nil {
		log.Fatalf("redis connect 1: %s\n", err)
	}

	router := gin.Default()

	router.HEAD("/heartbeat", func(c *gin.Context) {
		c.JSONP(200, "ok")
		return
	})

	router.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, DefaultUrl)
	})

	router.GET("/:key", func(c *gin.Context) {
		key := c.Param("key")

		target, err := rdb.HGet(c, RedisKeyShortUrl, key).Result()

		if err == nil && target != "" {
			log.Println(RedisKeyShortUrl, key, "path", target)
			c.Redirect(http.StatusMovedPermanently, target)
			return
		} else {
			log.Println(RedisKeyShortUrl, key, "err", err)
			c.Redirect(http.StatusMovedPermanently, DefaultUrl)
			return
		}

	})

	srv := &http.Server{
		Addr:    ":9998",
		Handler: router,
	}

	go func() {
		// 服务连接
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := rdb.Close(); err != nil {
		log.Fatal("redis1 close:", err)
	}

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}

	log.Println("Server exiting")
}

func Md5(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}
